package com.ruoyi.system.saleorder.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.ruoyi.common.constant.ExceptionConstants;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.financial.mapper.FinanceMapper;
import com.ruoyi.system.V2.goodInfo.service.IGoodsInfoService;
import com.ruoyi.system.model.domain.Finance;
import com.ruoyi.system.model.domain.GoodsInfo;
import com.ruoyi.system.saleorder.domain.SaleGoodsAfterReq;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.system.saleorder.mapper.SaleGoodsAfterMapper;
import com.ruoyi.system.saleorder.domain.SaleGoodsAfter;
import com.ruoyi.system.saleorder.service.ISaleGoodsAfterService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 售后Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-07
 */
@Service
public class SaleGoodsAfterServiceImpl implements ISaleGoodsAfterService {
    @Autowired
    private SaleGoodsAfterMapper saleGoodsAfterMapper;

    @Autowired
    private IGoodsInfoService goodsInfoService;

    @Autowired
    private FinanceMapper financeMapper;

    /**
     * 查询售后
     *
     * @param id 售后主键
     * @return 售后
     */
    @Override
    public SaleGoodsAfter selectSaleGoodsAfterById(Long id) {
        return saleGoodsAfterMapper.selectSaleGoodsAfterById(id);
    }

    /**
     * 查询售后列表
     *
     * @param saleGoodsAfter 售后
     * @return 售后
     */
    @Override
    public List<SaleGoodsAfter> selectSaleGoodsAfterList(SaleGoodsAfterReq saleGoodsAfter) {
        return saleGoodsAfterMapper.selectSaleGoodsAfterListTwo(saleGoodsAfter);
    }

    /**
     * 新增售后
     *
     * @param saleGoodsAfter 售后
     * @return 结果
     */
    @Override
    public int insertSaleGoodsAfter(SaleGoodsAfter saleGoodsAfter) {
        saleGoodsAfter.setCreateTime(DateUtils.getNowDate());
        return saleGoodsAfterMapper.insertSaleGoodsAfter(saleGoodsAfter);
    }

    /**
     * 修改售后
     *
     * @param saleGoodsAfter 售后
     * @return 结果
     */
    @Override
    public int updateSaleGoodsAfter(SaleGoodsAfter saleGoodsAfter) {
        if (StringUtils.isNotEmpty(saleGoodsAfter.getReturnNo())) {
            checkNo(saleGoodsAfter.getReturnNo(), saleGoodsAfter.getId());
        }
        if (StringUtils.isNotEmpty(saleGoodsAfter.getRepayNo())) {
            checkNo(saleGoodsAfter.getRepayNo(), saleGoodsAfter.getId());
        }
        return saleGoodsAfterMapper.updateSaleGoodsAfter(saleGoodsAfter);
    }

    /**
     * 转处理
     *
     * @param id 售后
     * @return 结果
     */
    @Override
    public int dispose(Long id) {
        SaleGoodsAfter goodsAfter = saleGoodsAfterMapper.selectSaleGoodsAfterById(id);
        if (Objects.isNull(goodsAfter)) {
            throw new GlobalException(ExceptionConstants.SALE_ORDER_AFTER_NULL);
        }
        if (!Objects.equals(goodsAfter.getAfterStatus(), 1)) {
            throw new GlobalException(ExceptionConstants.SALE_ORDER_AFTER_STATUS_ERROR);
        }
        SaleGoodsAfter after = new SaleGoodsAfter();
        after.setId(id);
        after.setAdminId(SecurityUtils.getUserId());
        after.setAfterStatus(2);
        return updateSaleGoodsAfter(after);
    }

    /**
     * 批量删除售后
     *
     * @param ids 需要删除的售后主键
     * @return 结果
     */
    @Override
    public int deleteSaleGoodsAfterByIds(Long[] ids) {
        return saleGoodsAfterMapper.deleteSaleGoodsAfterByIds(ids);
    }

    /**
     * 删除售后信息
     *
     * @param id 售后主键
     * @return 结果
     */
    @Override
    public int deleteSaleGoodsAfterById(Long id) {
        return saleGoodsAfterMapper.deleteSaleGoodsAfterById(id);
    }

    /**
     * 转售后  异步
     *
     * @param goodsInfo 商品主键
     */
    @Async
    @Override
    public void pushAfter(GoodsInfo goodsInfo, int taskType, Long userId) {

        SaleGoodsAfter goodsAfter = new SaleGoodsAfter();
        conversionToSaleGoodsAfter(goodsInfo, goodsAfter);
        Finance finance = new Finance();
        finance.setField4(String.valueOf(goodsInfo.getId()));
        finance.setDel(0);
        List<Finance> finances = financeMapper.selectFinanceList(finance);
        if (CollectionUtils.isNotEmpty(finances)) {
            for (Finance finance1 : finances) {
                if (StringUtils.equals(finance1.getIotype(), "2") && Objects.equals(finance1.getBillType(),9l) ) {
                    conversionToSaleGoodsAfterMCHU(finance1, goodsAfter);
                } else if (Objects.equals(finance1.getBillType(),13l) ){
                    conversionToSaleGoodsAfterMSHOU(finance1, goodsAfter);
                }
            }
            BigDecimal salePrice = Objects.isNull(goodsAfter.getSalePrice())?new BigDecimal(0):goodsAfter.getSalePrice();
            BigDecimal costPrice = Objects.isNull(goodsAfter.getCostTotalPrice())?new BigDecimal(0):goodsAfter.getCostTotalPrice();
            goodsAfter.setRise(salePrice.subtract(costPrice));
        }
        goodsAfter.setAfterStatus(2);
        goodsAfter.setType(taskType);
        goodsAfter.setCreateId(userId);
        goodsAfter.setRemark(goodsInfo.getRemark());
        goodsAfter.setDes(goodsInfo.getImportantRemark());
        goodsAfter.setTaskStatus(goodsInfo.getProblemDes());
        if (taskType == 2) {
            BigDecimal decimal = new BigDecimal("0");
            if (Objects.nonNull(goodsAfter.getSalePrice())) {
                decimal.add(goodsAfter.getSalePrice());
            }
            if (Objects.nonNull(goodsAfter.getCostTotalPrice())) {
                decimal.subtract(goodsAfter.getCostTotalPrice());
            }
            goodsAfter.setDownPrice(decimal);
        }
        insertSaleGoodsAfter(goodsAfter);
    }

    @Override
    public int overTask(Long id) {
        SaleGoodsAfter after = saleGoodsAfterMapper.selectSaleGoodsAfterById(id);
        if (Objects.isNull(after)) {
            throw new GlobalException(ExceptionConstants.SALE_ORDER_AFTER_NULL);
        }
        if (StringUtils.isEmpty(after.getOverDes())) {
            throw new GlobalException(ExceptionConstants.SALE_ORDER_AFTER_PARAM_ERROR);
        }
        after.setOverTime(new Date());
        after.setAfterStatus(3);
        after.setOverId(SecurityUtils.getUserId());
        return saleGoodsAfterMapper.updateSaleGoodsAfter(after);
    }
    /**
     * 完结人  overId
     * 完结方案  overDes
     * 完结日期  overTime
     * 回款图片 returnImg
     * 回款金额 returnPrice
     * 还号日期 returnTime
     * 赔付图片 repayImg
     * 赔付金额 repayPrice
     * des des
     *
     * @param info
     * @return
     */
    /**
     * 商品信息
     *
     * @param info
     * @param after
     * @return
     */
    public SaleGoodsAfter conversionToSaleGoodsAfter(GoodsInfo info, SaleGoodsAfter after) {
        after.setGoodsId(info.getId());
        after.setGameId(info.getGameId());
        after.setGameName(info.getGameName());
        after.setChannel(info.getSaleChannel());
        after.setAccountNumber(info.getAccountNumber());
        after.setUpTime(info.getCreateTime());
        after.setProblemType(info.getProblemTypeName());
        after.setPrice(info.getPrice());
        after.setRecyclerName(info.getRecyclerName());

        return after;
    }

    /**
     * 收号
     *
     * @param info
     * @param after
     * @return
     */
    public SaleGoodsAfter conversionToSaleGoodsAfterMSHOU(Finance info, SaleGoodsAfter after) {
        after.setSaleTime(info.getCreateTime());
        after.setCostPrice(converToBDC(info.getField7()));
        after.setCostOtherPrice(converToBDC(info.getField8()));
        after.setCostRepayPrice(converToBDC(info.getField2()));
        after.setCostTotalPrice(info.getPrice());
        return after;
    }

    /**
     * 出号
     *
     * @param info
     * @param after
     * @return
     */
    public SaleGoodsAfter conversionToSaleGoodsAfterMCHU(Finance info, SaleGoodsAfter after) {
        after.setSaleTime(info.getCreateTime());
        after.setSalePrice(info.getPrice());
        after.setChannel(info.getField10());
        return after;
    }

    public BigDecimal converToBDC(String decimalStr) {
        return new BigDecimal(StringUtils.isNotEmpty(decimalStr) ? decimalStr : "0");
    }

    @Override
    public void checkNo(String no,Long id) {
        List<SaleGoodsAfter> list = saleGoodsAfterMapper.checkNo(no);
        if (CollectionUtils.isNotEmpty(list)) {
            for (SaleGoodsAfter saleGoodsAfter : list) {
                if (!Objects.equals(saleGoodsAfter.getId(),id)){
                    throw new GlobalException("单号已存在,不可重复使用");
                }
            }
        }
    }
}
